<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="书籍名称" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入书籍名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拍卖状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择拍卖状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['merchant:auction:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['merchant:auction:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['merchant:auction:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="auctionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80"/>
      <el-table-column label="书籍名称" align="center">
        <template #default="scope">
          {{ scope.row.product?.name || scope.row.bookName || '未知书籍' }}
        </template>
      </el-table-column>
      <el-table-column label="起拍价" align="center" prop="startPrice">
        <template #default="scope">
          ¥{{ scope.row.startPrice }}
        </template>
      </el-table-column>
      <el-table-column label="当前价格" align="center" prop="currentPrice">
        <template #default="scope">
          ¥{{ scope.row.currentPrice }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'warning' : scope.row.status === 2 ? 'info' : 'danger'">
            {{ scope.row.status === 1 ? '进行中' : scope.row.status === 0 ? '未开始' : scope.row.status === 2 ? '已结束' : '已取消' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="success"
            icon="VideoPlay"
            size="small"
            @click="handleStart(scope.row)"
            v-hasPermi="['merchant:auction:start']"
          >开始</el-button>
          <el-button
            v-if="scope.row.status === 1"
            type="warning"
            icon="VideoPause"
            size="small"
            @click="handleEnd(scope.row)"
            v-hasPermi="['merchant:auction:end']"
          >结束</el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            icon="CircleClose"
            size="small"
            @click="handleCancel(scope.row)"
            v-hasPermi="['merchant:auction:cancel']"
          >取消</el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="primary"
            icon="Edit"
            size="small"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:auction:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            icon="Delete"
            size="small"
            @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:auction:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拍卖对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="书籍选择" prop="productId">
          <el-select 
            v-model="form.productId" 
            placeholder="请选择书籍" 
            :loading="bookLoading"
            filterable
          >
            <el-option
              v-for="book in bookOptions"
              :key="book.id"
              :label="book.name"
              :value="book.id"
            >
              <span style="float: left">{{ book.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ book.isbn }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起拍价" prop="startPrice">
          <el-input-number v-model="form.startPrice" :min="0" :precision="2" :step="0.01" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="加价幅度" prop="stepPrice">
          <el-input-number v-model="form.stepPrice" :min="0.01" :precision="2" :step="0.01" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <div class="flex-container">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: calc(100% - 100px)"
            />
            <el-button link type="primary" @click="setDefaultStartTime">设为1分钟后</el-button>
          </div>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <div class="flex-container">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: calc(100% - 100px)"
            />
            <el-button link type="primary" @click="setDefaultEndTime">设为5分钟后</el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.flex-container {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { 
  getAuctionList, 
  getAuctionDetail, 
  addAuction, 
  updateAuction, 
  deleteAuction,
  startAuction,
  endAuction,
  cancelAuction
} from "@/api/merchant/auction"
import { listBook } from "@/api/merchant/book"
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { useRouter } from 'vue-router'

const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const open = ref(false)
const title = ref("")
const auctionList = ref([])
const bookOptions = ref([])
const bookLoading = ref(false)
const formRef = ref(null)
const router = useRouter()

// 状态数据字典
const statusOptions = ref([
  { value: 0, label: "未开始" },
  { value: 1, label: "进行中" },
  { value: 2, label: "已结束" },
  { value: 3, label: "已取消" }
])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  bookName: undefined,
  status: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  productId: undefined,
  bookName: undefined,
  startPrice: undefined,
  stepPrice: undefined,
  currentPrice: undefined,
  startTime: undefined,
  endTime: undefined,
  status: 0,
  remark: undefined
})

// 表单校验规则
const rules = ref({
  productId: [
    { required: true, message: "请选择书籍", trigger: "change" }
  ],
  startPrice: [
    { required: true, message: "请输入起拍价", trigger: "blur" }
  ],
  stepPrice: [
    { required: true, message: "请输入加价幅度", trigger: "blur" }
  ],
  startTime: [
    { required: true, message: "请选择开始时间", trigger: "blur" }
  ],
  endTime: [
    { required: true, message: "请选择结束时间", trigger: "blur" }
  ]
})

// 获取书籍列表
const getBookList = async () => {
  bookLoading.value = true
  try {
    const response = await listBook()
    if (response.code === 200) {
      bookOptions.value = response.rows || []
    } else {
      ElMessage.error(response.msg || '获取书籍列表失败')
    }
  } catch (error) {
    console.error("获取书籍列表失败:", error)
    ElMessage.error('获取书籍列表失败')
  } finally {
    bookLoading.value = false
  }
}

// 监听 bookId 的变化
watch(() => form.value.productId, (newVal) => {
  if (newVal) {
    const selectedBook = bookOptions.value.find(book => book.id === newVal)
    if (selectedBook) {
      form.value.bookName = selectedBook.name
    }
  } else {
    form.value.bookName = undefined
  }
})

// 查询拍卖列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getAuctionList(queryParams.value)
    // 处理数据，确保每条记录都有书籍名称
    auctionList.value = response.rows.map(item => ({
      ...item,
      bookName: item.product?.name || item.bookName || '未知书籍'
    }))
    total.value = response.total
  } catch (error) {
    console.error("获取拍卖列表失败:", error)
  } finally {
    loading.value = false
  }
}

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    productId: undefined,
    bookName: undefined,
    startPrice: undefined,
    stepPrice: undefined,
    currentPrice: undefined,
    startTime: undefined,
    endTime: undefined,
    status: 0,
    remark: undefined
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    bookName: undefined,
    status: undefined
  }
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = async () => {
  reset()
  open.value = true
  title.value = "添加拍卖"
  await getBookList()
}

// 修改按钮操作
const handleUpdate = async (row) => {
  reset()
  const id = row.id || ids.value[0]
  try {
    await getBookList()
    const response = await getAuctionDetail(id)
    if (response.code === 200) {
      Object.assign(form.value, response.data)
    } else {
      ElMessage.error(response.msg || '获取拍卖详情失败')
    }
    open.value = true
    title.value = "修改拍卖"
  } catch (error) {
    console.error("获取拍卖详情失败:", error)
    ElMessage.error('获取拍卖详情失败')
  }
}

// 提交按钮
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // 设置当前价格为起拍价
    form.value.currentPrice = form.value.startPrice
    if (form.value.id) {
      await updateAuction(form.value)
      ElMessage.success("修改成功")
    } else {
      await addAuction(form.value)
      ElMessage.success("新增成功")
    }
    open.value = false
    getList()
  } catch (error) {
    console.error("提交失败:", error)
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  const auctionIds = row.id || ids.value
  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？')
    await deleteAuction(auctionIds)
    getList()
    ElMessage.success("删除成功")
  } catch (error) {
    console.error("删除失败:", error)
    // 检查是否是外键约束错误
    if (error.response?.data?.msg?.includes('foreign key constraint fails')) {
      ElMessage.error("该拍卖已有竞拍记录，无法删除")
    } else {
      ElMessage.error(error.response?.data?.msg || "删除失败，请重试")
    }
  }
}

// 开始拍卖
const handleStart = async (row) => {
  try {
    await ElMessageBox.confirm('是否确认开始该拍卖？')
    await startAuction(row.id)
    getList()
    ElMessage.success("已开始拍卖")
  } catch (error) {
    console.error("开始拍卖失败:", error)
  }
}

// 结束拍卖
const handleEnd = async (row) => {
  try {
    await ElMessageBox.confirm('是否确认结束该拍卖？')
    const response = await endAuction(row.id)
    getList()
    ElMessage.success("已结束拍卖")
    
    // 如果返回了订单ID，说明有人中标，跳转到订单详情页
    const orderId = response.data
    if (orderId) {
      ElMessageBox.confirm('拍卖已结束，是否查看订单详情？', '提示', {
        confirmButtonText: '查看订单',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        router.push({
          path: '/orders/order/detail',
          query: { orderId }
        })
      }).catch(() => {})
    }
  } catch (error) {
    console.error("结束拍卖失败:", error)
    if (error.toString() !== 'Error: cancel') {  // 不是用户取消的情况
      ElMessage.error(error.response?.data?.msg || "结束拍卖失败，请重试")
    }
  }
}

// 取消拍卖
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('是否确认取消该拍卖？')
    await cancelAuction(row.id)
    getList()
    ElMessage.success("已取消拍卖")
  } catch (error) {
    console.error("取消拍卖失败:", error)
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 格式化日期时间
const formatDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 设置默认开始时间（当前时间1分钟后）
const setDefaultStartTime = () => {
  const now = new Date()
  now.setMinutes(now.getMinutes() + 1)
  form.value.startTime = formatDateTime(now)
}

// 设置认结束时间（当前时间5分钟后）
const setDefaultEndTime = () => {
  const now = new Date()
  now.setMinutes(now.getMinutes() + 5)
  form.value.endTime = formatDateTime(now)
}

// 检查并更新拍卖状态
const checkAuctionStatus = async () => {
  const now = new Date()
  let hasChanges = false
  
  for (const auction of auctionList.value) {
    const startTime = new Date(auction.startTime)
    const endTime = new Date(auction.endTime)
    
    try {
      if (auction.status === 0 && now >= startTime) {
        // 如果未开始且已到开始时间，则自动开始
        await startAuction(auction.id)
        hasChanges = true
      } else if (auction.status === 1 && now >= endTime) {
        // 如果进行中且已到结束时间，则自动结束
        await endAuction(auction.id)
        hasChanges = true
      }
    } catch (error) {
      console.error("自动更新拍卖状态失败:", error)
    }
  }
  
  // 如果有状态变化，立即刷新列表
  if (hasChanges) {
    await getList()
  }
}

// 定时器引用
let statusCheckTimer = null

onMounted(async () => {
  await getList()
  // 立即检查一次状态
  await checkAuctionStatus()
  // 启动定时器，每10秒检查一次
  statusCheckTimer = setInterval(async () => {
    await checkAuctionStatus()
  }, 10000)
})

onUnmounted(() => {
  // 清除定时器
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer)
  }
})
</script> 